package com.acquisition.task.util;

import java.math.BigInteger;

/**
 * 字节数组工具类
 *
 * @author wuqiwei
 * @date 2021/07/20
 */
public class ByteUtils {

    private static byte toByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 十六进制字符串转byte数组
     *
     * @param hex 十六进制字符串
     * @return byte数组
     */
    public static byte[] hexStrToByteArr(String hex) {
        hex = hex.toUpperCase().replaceAll(" ", "");
        byte[] result = new byte[hex.length() / 2];
        char[] chars = hex.toCharArray();
        for (int i = 0; i < hex.length() / 2; i++) {
            result[i] = (byte) (toByte(chars[i * 2]) << 4 | toByte(chars[i * 2 + 1]));
        }
        return result;
    }

    /**
     * byte数组转十六进制字符串
     *
     * @param bytes byte数组
     * @return 十六进制字符串
     */
    public static String byteArrToHexStr(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        return result.toString().toUpperCase().replaceAll(" ", "");
    }

    /**
     * 字节数组转int数组
     *
     * @param bytes 字节数组
     * @return int数组
     */
    public static int[] byteArrToIntArr(byte[] bytes) {
        int[] arr = new int[bytes.length / 2];
        for (int i = 0, j = 0; i < arr.length; i++, j += 2) {
            arr[i] = ((bytes[j] & 0xff) << 8) | (bytes[j + 1] & 0xff);
        }
        return arr;
    }

    /**
     * 十六进制编码转float
     *
     * @param hex 十六进制字符串
     * @return float
     */
    public static float hexToFloat(String hex) {
        return Float.intBitsToFloat(new BigInteger(hex, 16).intValue());
    }

    /**
     * 十六进制编码转double
     *
     * @param hex 十六进制字符串
     * @return double
     */
    public static double hexToDouble(String hex) {
        return Double.longBitsToDouble(new BigInteger(hex, 16).longValue());
    }

    /**
     * crc校验
     *
     * @param data 校验数据
     * @return CRC
     */
    public static String crc16(String data) {
        char[] charArray = data.toCharArray();
        int i, j, crc, check;
        crc = 0xFFFF;
        for (i = 0; i < data.length(); i++) {
            crc = (crc >> 8) ^ charArray[i];
            for (j = 0; j < 8; j++) {
                check = crc & 0x0001;
                crc >>= 1;
                if (check == 0x0001) {
                    crc ^= 0xA001;
                }
            }
        }
        return String.format("%04X", crc);
    }

}
